import { defineConfig, loadEnv } from 'vite'
import path from 'path'
import createVitePlugins from './vitePlugins'

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  const { VITE_APP_PUBLIC_PATH, NODE_ENV } = env
  return {
    base: VITE_APP_PUBLIC_PATH,
    plugins: createVitePlugins(env, command === 'build'),
    build: {
      outDir: 'ocrm',
      assetsDir: "assets",
      sourcemap: command != 'build',
      chunkSizeWarningLimit: 1500,
      // 清除console和debugger
      minify: 'terser',
      terserOptions: {
        compress: {
          pure_funcs: ['console.log'],  // 只删除 console.log  
          drop_debugger: true, // 删除 debugger
        }
      },
      // 配置打包文件路径和命名
      rollupOptions: {
        output: {
          // 超大静态资源拆分
          manualChunks(id){
            if(id.includes('node_modules')){
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          },
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
        }
      },
    },
    resolve: {
      alias: {
        // 设置路径
        '~': path.resolve(__dirname, './'),
        // 设置别名
        '@': path.resolve(__dirname, './src')
      },
      // https://cn.vitejs.dev/config/#resolve-extensions
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    // vite 相关配置
    server: {
      port: 8080,
      host: true,
      proxy: {
        // https://cn.vitejs.dev/config/#server-proxy
        '/api': {
          target: 'http://localhost:3000',
          changeOrigin: true,
          // rewrite: (p) => p.replace(/^\/api/, '/api')
        },
        // onProxyRes(proxyRes, req, res) {
        //   //在控制台显示真实代理地址---webpack才能用
        //   const realUrl = new URL(req.url || '',process.env.VUE_APP_BASE_API)?.href || ''
        //   proxyRes.headers['x-real-url'] = realUrl
        // },
      }
    },
    //fix:error:stdin>:7356:1: warning: "@charset" must be the first rule in the file
    css: {
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove();
                }
              }
            }
          }
        ]
      }
    }
  }
})
